package com.paydemo.pay.controller;

import com.paydemo.pay.entity.PayOrder;
import com.paydemo.pay.service.PayOrderService;
import com.paydemo.pay.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付控制器
 */
@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Resource
    private PayOrderService payOrderService;

    /**
     * 创建支付宝扫码支付订单
     */
    @PostMapping("/create")
    public Result<Map<String, Object>> createOrder(@RequestParam BigDecimal amount) {
        log.info("创建支付宝扫码支付订单，金额：{}", amount);
        return payOrderService.createAlipayQrCodeOrder(amount);
    }

    /**
     * 支付宝异步通知接口
     */
    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest request) {
        log.info("接收到支付宝异步通知");
        return payOrderService.handleAlipayNotify(request);
    }

    /**
     * 支付宝同步通知接口
     */
    @GetMapping("/return")
    public Result<Map<String, Object>> alipayReturn(HttpServletRequest request) {
        log.info("接收到支付宝同步通知");
        return payOrderService.handleAlipayReturn(request);
    }
    
    /**
     * 查询订单支付状态
     */
    @GetMapping("/query")
    public Result<Map<String, Object>> queryOrder(@RequestParam String orderNo) {
        log.info("查询订单支付状态: {}", orderNo);
        PayOrder payOrder = payOrderService.getByOrderNo(orderNo);
        
        if (payOrder == null) {
            return Result.error("订单不存在");
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("orderNo", payOrder.getOrderNo());
        result.put("amount", payOrder.getAmount());
        result.put("payStatus", payOrder.getPayStatus());
        
        // 如果已支付成功，返回交易号
        if (payOrder.getPayStatus() == 1 && payOrder.getTradeNo() != null) {
            result.put("tradeNo", payOrder.getTradeNo());
        }
        
        return Result.success("查询成功", result);
    }
} 